package com.gxa.consumer.service.impl;

import com.gxa.common.result.BusinessException;
import com.gxa.common.result.RestResponse;
import com.gxa.common.util.StringUtil;
import com.gxa.consumer.common.ConsumerErrorCode;
import com.gxa.consumer.config.RedisKey;
import com.gxa.consumer.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by zxd on 2020/2/3
 **/
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {


    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public RestResponse sendLoginSms(String phone)  {

     

        //1.生成验证码
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<6;i++){
            sb.append(new Random().nextInt(10));
        }
        //生成的验证码
        String code=sb.toString();

       log.info("code is {}:",code);

        //2.服务器存储验证码
        redisTemplate.boundValueOps(RedisKey.LOGIN_SMS +phone).set(code);

        //3.设置失效时间
        redisTemplate.boundValueOps(RedisKey.LOGIN_SMS +phone).expire(5*60,TimeUnit.SECONDS);

        //4.发送短信给用户
        //SendSms.sendSms(phone,code);

        return RestResponse.success();
    }

    @Override
    public void verifySmsCode(String mobile, String code) {

        String  serverCode = (String) redisTemplate.boundValueOps(RedisKey.LOGIN_SMS + mobile).get();

        if(StringUtil.isEmpty(serverCode)){
            throw new BusinessException(ConsumerErrorCode.E_140152);
        }

        if(!serverCode.equals(code)){
            throw new BusinessException(ConsumerErrorCode.E_140152);
        }

    }
}
